package housing.task6_web;

import housing.task1.actor.Address;
import housing.task3.dao.HsAddressDao;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

public class InputFromAddressForm extends javax.servlet.http.HttpServlet {
    private HsAddressDao addressDao;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        addressDao = (HsAddressDao) config.getServletContext().getAttribute(InitContextListener.CTX_ADDRESS_DAO);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final PrintWriter w = resp.getWriter();
        w.write("<html><body>");

        w.write("id= " + Arrays.toString(req.getParameterValues("address_id")) + "<br/>");
        w.write("street= " + Arrays.toString(req.getParameterValues("street")) + "<br/>");
        w.write("house= " + Arrays.toString(req.getParameterValues("house")) + "<br/>");
        w.write("flat= " + Arrays.toString(req.getParameterValues("flat")) + "<br/>");
        w.write("</body></html>");

        String id = req.getParameter("address_id");
        String street = req.getParameter("street");
        String house = req.getParameter("house");
        String flat = req.getParameter("flat");

        Address address = new Address(
                new Long(id),
                street,
                new Integer(house),
                new Integer(flat)
        );

        ArrayList<String> strings = new ArrayList<String>();
        strings.add(id);
        strings.add(street);
        strings.add(house);
        strings.add(flat);

        req.setAttribute("strings", strings);

        getServletContext().
                getRequestDispatcher("/getAddresses.jsp").forward(req, resp);


        /*JSNFactory factory = new JSNFactory();
        AbstractWriter jsnWriter = factory.createWriter();
        File file = new File(".\\src\\main\\resources\\test\\servlet.jsn");
        jsnWriter.setAddressOut(file);
        jsnWriter.write(address);

        JsnImporter imp = new JsnImporter();
        imp.importFile(addressDao, file);*/

    }
}
